# -*-coding=utf-8 -*-
"""
    @author:sirius
    @time:2018.1.4
"""
import math

# 计算余弦距离
# listUser2Score[2]=[(23,2,0),(43,0,1),(36,1,2)....]
# 表示用户2的应用安装列表（apps list）23,42,36（AppID）
# 用户2应用23电量消耗层级为2(高),网路消耗层级为0(低);
# 应用43电量消耗层级为0(低),网路消耗层级为1(中);
# 应用36电量消耗层级为1(中),网路消耗层级为2(高);
# dist = getCosDist(listUser2Score[userId], listUser2Score[neighbor])
def get_similarity(user_id, target, neighbor):
    # 余弦相似度计算公式系数
    sum_x = 0.0
    sum_y = 0.0
    sum_xy = 0.0
    sum_xy1 = 0.0
    sum_xy2 = 0.0
    # 目标用户安装的应用个数
    app_num4target = 0
    # 目标用户与"邻居"共同安装的应用个数
    common_app_num = 0
    weight_dict = {}
    with open('../period/cache/weight.txt') as weight_obj:
        weight_dict = eval(weight_obj.read())

    for t_event in target:
        app_num4target += 1
        for n_event in neighbor:
            # key1[0]表示app id，key1[1]表示对app的评分
            # 如果是两个用户共同使用的一个应用
            if t_event[1] == n_event[1]:
                if t_event[1] in weight_dict[user_id]:
                    weight_value = weight_dict[user_id][t_event[1]]
                else:
                    weight_value = 1
                common_app_num += 1

                sum_x += weight_value * float(t_event[3]) * float(n_event[3])
                sum_y += weight_value * float(t_event[2]) * float(n_event[2])
                sum_xy1 += weight_value * (float(t_event[3]) * float(t_event[3]) + float(t_event[2]) * float(t_event[2]))
                sum_xy2 += weight_value * (float(n_event[3]) * float(n_event[3]) + float(n_event[2]) * float(n_event[2]))

            sum_xy = math.sqrt(sum_xy1) * math.sqrt(sum_xy2)

    if sum_x + sum_y == 0.0:
        return 0

    return (sum_x + sum_y) * common_app_num / sum_xy / app_num4target
